﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using NetSurveillance.WebApp.Binders;
using NetSurveillance.WebApp.DataServices.Models;
using NetSurveillance.WebApp.Exts;
using NetSurveillance.WebApp.Models;
using System.Linq;
using NetSurveillance.WebApp.Utilities;
using Resources;
using Webdiyer.WebControls.Mvc;

namespace NetSurveillance.WebApp.Controllers
{
    public class SystemController : BaseController
    {

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            ViewBag.IsAdmin = CurrentUser.UserType == UserType.Administrator;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult AccountManage(int pageIndex = 1)
        {
            var users =
                DataProvider.UserService.GetAllModels().OrderByDescending(p => p.LastModifiedTime).
                    ToPagedList(pageIndex, PresetValues.DefaultPageSize);
            return View(users);
        }

        [HttpPost]
        public ActionResult DeleteAccount(long accountId)
        {
            var result = DataProvider.UserService.Delete(accountId);
            return Json(new AjaxResult(result.ExecutedSuccess, result.Message));
        }

        public ActionResult SaveAccount(long? accountId = null)
        {
            var user = accountId.HasValue ? DataProvider.UserService.GetModelById(accountId.Value) : new User();
            var userPms = accountId.HasValue
                              ? DataProvider.UserService.GetAcctPermission(accountId.Value)
                              : null;
            var saveModel = new SaveAccountModel
                {
                    UserName = user.UserName,
                    Email = user.Email,
                    RealName = user.RealName,
                    Phone = user.Phone,
                    HaveDeletePms =
                        userPms != null && (userPms.Permission & PermissionType.Delete) != 0,
                    UserType = (int) user.UserType
                };
            if (accountId.HasValue)
                saveModel.Id = user.Id;
            return View(saveModel);
        }

        [HttpPost]
        public ActionResult SaveAccount(SaveAccountModel saveAccountModel)
        {
            if (!saveAccountModel.Id.HasValue)
                ModelState.Remove("OldPassword");
            if (ModelState.IsValid)
            {
                var userInDb =
                    saveAccountModel.Id.HasValue
                        ? DataProvider.UserService.GetAllModels(false,
                                                                p =>
                                                                p.Id != saveAccountModel.Id.Value &&
                                                                p.UserName == saveAccountModel.UserName)
                        : DataProvider.UserService.GetAllModels(false,
                                                                p =>
                                                                p.UserName == saveAccountModel.UserName);
                if (!userInDb.Any())
                {
                    var user = saveAccountModel.Id.HasValue ? DataProvider.UserService.GetModelById(saveAccountModel.Id.Value) : new User();
                    if (saveAccountModel.Id.HasValue && saveAccountModel.OldPassword != user.Password)
                    {
                        ModelState.AddModelError("PasswordIncorrect", MessageResource.Old_Password_is_incorrect);
                    }
                    else
                    {
                        user.UserName = saveAccountModel.UserName;
                        user.Email = saveAccountModel.Email;
                        user.Password = saveAccountModel.NewPassword;
                        user.RealName = saveAccountModel.RealName;
                        user.Phone = saveAccountModel.Phone;
                        user.UserType = (UserType)saveAccountModel.UserType;
                        user.LastModifiedTime = DateTime.Now;
                        DataProvider.UserService.Save(user);
                        DataProvider.UserService.SaveAcctPermission(user.Id,
                                                                    saveAccountModel.HaveDeletePms
                                                                        ? PermissionType.Delete
                                                                        : PermissionType.None);
                        return RedirectToAction("AccountManage");
                    }
                }
                ModelState.AddModelError("",
                                         string.Format("用户:{0}已存在，请更换名字再试", saveAccountModel.UserName));
            }
            ModelState.AddModelError("", MessageResource.Save_Error);
            return View();
        }

        public ActionResult CaseManage(int pageIndex = 1)
        {
            //todo:普通用户需要显示具有可读或可读写权限的案件、并且当前会话之类的地方也要让对该权限进行匹配
            var cases = CurrentUser.UserType == UserType.Administrator
                            ? DataProvider.CaseService.GetAllModels()
                                          .OrderByDescending(p => p.LastModifiedTime)
                            : DataProvider.CaseService.GetCasesByCreatedUser(CurrentUser.Id)
                                          .OrderByDescending(p => p.LastModifiedTime);
            var casePmsDic = new Dictionary<long, IList<CasePermission>>();
            foreach (var caseModel in cases)
            {
                var casePmses = DataProvider.CaseService.GetCasePermissions(caseModel.Id).Where(p=>p.Permission != PermissionType.None);
                casePmsDic.Add(caseModel.Id, casePmses.ToList());
            }
            ViewBag.CasePmsDic = casePmsDic;
            var casePageModel = cases.ToPagedList(pageIndex, PresetValues.DefaultPageSize);
            if (CurrentCase != null)
            {
                ViewBag.CurrentCaseId = CurrentCase.Id;
            }
            return View(casePageModel ?? new PagedList<Case>(new List<Case>(), pageIndex, PresetValues.DefaultPageSize));
        }

        public ActionResult SaveCase(long caseId = 0)
        {
            if (caseId == 0)
                return View();
            var caseEntry = DataProvider.CaseService.GetModelById(caseId);
            return View(new CaseModel { Desc = caseEntry.Desc, Name = caseEntry.Name, Id = caseEntry.Id });
        }

        [HttpPost]
        public ActionResult SaveCase(CaseModel caseModel)
        {
            if (ModelState.IsValid)
            {
                long caseId = caseModel.Id.HasValue ? caseModel.Id.Value : -1;
                bool hasSameName = DataProvider.CaseService.GetAllModels(false,
                                                                        p =>
                                                                        p.Name == caseModel.Name &&
                                                                        (!caseModel.Id.HasValue || p.Id != caseId)).Any();
                if (hasSameName)
                {
                    ModelState.AddModelError("", MessageResource.CaseIsExists);
                    return View(caseModel);
                }
                var caseEntry = caseModel.Id.HasValue ? DataProvider.CaseService.GetModelById(caseId) : new Case();
                if (caseModel.Id.HasValue)
                    caseEntry.LastModifiedTime = DateTime.Now;
                else
                    caseEntry.CreateUserId = CurrentUser.Id;
                caseEntry.Name = caseModel.Name;
                caseEntry.Desc = caseModel.Desc;
                DataProvider.CaseService.Save(caseEntry);
                return RedirectToAction("CaseManage");
            }
            ModelState.AddModelError("", MessageResource.Save_Error);
            return View(caseModel);
        }

        [HttpPost]
        public ActionResult DeleteCase(long caseId)
        {
            var result = DataProvider.CaseService.Delete(caseId);
            return Json(new AjaxResult(result.ExecutedSuccess, result.Message));
        }

        public ActionResult LoadPmsConfig(long caseId)
        {
            var casePmsList = DataProvider.CaseService.GetCasePermissions(caseId);
            return PartialView("_PmsConfig", casePmsList);
        }

        [HttpPost]
        public ActionResult SavePmsConfig([JsonBinder]ICollection<CasePermission> casePermissions)
        {
            if (casePermissions == null || casePermissions.Count == 0)
                return CamelCaseJson(new AjaxResult(false, "请至少设置一个权限"));
            var serviceResult = DataProvider.CaseService.SaveCasePermission(casePermissions);
            return CamelCaseJson(new AjaxResult(serviceResult.ExecutedSuccess, serviceResult.Message));
        }

        public ActionResult MonitorSetting()
        {
            var monitorModel = DataProvider.MonitorSettingService.GetFirstMonitorSetting() ??
                               new MonitorSetting {DefaultPageSize = PresetValues.DefaultPageSize};
            string protocolArr = string.Join(",", DataProvider.ProtocolsService.GetAllModels().Select(p => p.ProtocolType));
            ViewData["protocol"] = protocolArr;
            ViewBag.SupportProtocols = SupportUtility.GetSupportProtocols();
            return View(monitorModel);
        }

        [HttpPost]
        public ActionResult MonitorSetting(MonitorSetting monitorSetting, string[] protocols)
        {
            var msEle = ActionXmlUtility.Instance.CreateMonitorSettingElement(monitorSetting, protocols);
            var actionEle =
                ActionXmlUtility.Instance.GeneratorActionXml(ActionXmlUtility.Instance.CreateActionRootElement(), msEle);
            if (!Connector.SendAction(actionEle, PresetValues.MonitorIp, PresetValues.MonitorPort))
            {
                ModelState.AddModelError("", MessageResource.SendActionError);
                return View(monitorSetting);
            }
            var msInDb = monitorSetting.Id > 0
                             ? DataProvider.MonitorSettingService.GetModelById(monitorSetting.Id)
                             : monitorSetting;
            if (monitorSetting.Id > 0)
            {
                msInDb.IsSaveWebContent = monitorSetting.IsSaveWebContent;
                msInDb.SaveFileDay = monitorSetting.SaveFileDay;
                msInDb.SaveFileExts = monitorSetting.SaveFileExts;
                msInDb.MinSize = monitorSetting.MinSize;
                msInDb.MaxSize = monitorSetting.MaxSize;
            }
            var serviceResult = DataProvider.MonitorSettingService.Save(monitorSetting);
            ViewData["protocol"] = protocols == null ? null : string.Join(",", protocols);
            ViewBag.SupportProtocols = SupportUtility.GetSupportProtocols();
            if(serviceResult.ExecutedSuccess)
            {
                serviceResult = DataProvider.ProtocolsService.SaveAllProtocols(protocols);
                if (serviceResult.ExecutedSuccess)
                {
                    ModelState.Clear();
                    ModelState.AddModelError("", MessageResource.Save_Success);
                    return View(monitorSetting);
                }
            }
            ModelState.AddModelError("", MessageResource.Save_Error);
            return View(monitorSetting);
        }

        public ActionResult FieldSetting()
        {
            var monitorModel = DataProvider.MonitorSettingService.GetFirstMonitorSetting();
            var displayFields = string.Join(",",
                                            DataProvider.DisplayFieldService.GetAllModels().Select(p => p.FieldName));
            ViewData["displayFields"] = displayFields;

            return View(monitorModel ?? new MonitorSetting {Id = -1,DefaultPageSize = PresetValues.DefaultPageSize});
        }

        [HttpPost]
        public ActionResult FieldSetting(MonitorSetting monitorSetting, string[] displayFields)
        {
            var msInDb = monitorSetting.Id > 0
                             ? DataProvider.MonitorSettingService.GetModelById(monitorSetting.Id)
                             : monitorSetting;
            if (monitorSetting.Id > 0)
            {
                msInDb.DefaultPageSize = monitorSetting.DefaultPageSize;
                msInDb.IsShowTitleRecord = monitorSetting.IsShowTitleRecord;
            }
            var serviceResult = DataProvider.MonitorSettingService.Save(msInDb);
            if (displayFields != null)
                ViewData["displayFields"] = string.Join(",", displayFields);
            if (serviceResult.ExecutedSuccess)
            {
                serviceResult = DataProvider.DisplayFieldService.SaveAllFields(displayFields);
                if (serviceResult.ExecutedSuccess)
                {
                    ApplicationContainer.Add(PresetValues.ApplicationKeys.PageSize, monitorSetting.DefaultPageSize);
                    ApplicationContainer.Add(PresetValues.ApplicationKeys.IsShowNoTitleRecord,
                                             monitorSetting.IsShowTitleRecord);
                    ModelState.Clear();
                    ModelState.AddModelError("", MessageResource.Save_Success);
                    return View(monitorSetting);
                }
            }
            ModelState.AddModelError("", MessageResource.Save_Error);
            return View(monitorSetting);
        }

        public ActionResult ADSLSetting()
        {
            var monitorModel = DataProvider.MonitorSettingService.GetFirstMonitorSetting();
            var adslModel = new AdslModel();
            adslModel.MergeFrom(monitorModel);
            return View(adslModel);
        }

        [HttpPost]
        public ActionResult ADSLSetting(AdslModel adslModel)
        {
            if (ModelState.IsValid)
            {
                var monitorSetting = new MonitorSetting();
                if (adslModel.Id > 0)
                {
                    monitorSetting = DataProvider.MonitorSettingService.GetModelById(adslModel.Id);
                }
                monitorSetting.MergeFrom(adslModel);
                var iaId = ApplicationContainer.Read<long?>(PresetValues.InteractiveKeys.SetAdsl);
                var ia = iaId.HasValue ? DataProvider.InteractiveService.GetModelById(iaId.Value) : null;
                if (ia != null)
                {
                    if (ia.InteractiveStatus == InteractiveStatus.End)
                    {
                        var sr = DataProvider.MonitorSettingService.Save(monitorSetting);
                        RemoveSetAdslCache();
                        return
                            CamelCaseJson(sr.ExecutedSuccess
                                              ? new AjaxResult(true) {Expandos = new {monitorSetting.Id}}
                                              : new AjaxResult(false, sr.Message));
                    }
                    var setAdslTime = ApplicationContainer.Read<DateTime>(PresetValues.ApplicationKeys.SetAdslTime);
                    if ((DateTime.Now - setAdslTime).TotalSeconds >= PresetValues.Timeouts.SetAdsl)
                    {
                        RemoveSetAdslCache();
                        SaveInteractiveTimeout(ia);
                        return CamelCaseJson(new AjaxResult(false, "设置ADSL超时"));
                    }
                    if (ia.InteractiveStatus == InteractiveStatus.Error)
                    {
                        RemoveSetAdslCache();
                        DataProvider.MonitorSettingService.Save(monitorSetting);
                        string errorMsg = XmlResource.GetItactCodeValue(ia.ErrorCode);
                        var ajaxResult =
                            new AjaxResult(false, errorMsg) {Expandos = new {monitorSetting.Id}};
                        return CamelCaseJson(ajaxResult);
                    }
                    return CamelCaseJson(AjaxResult.TrueResult);
                }
                bool sendActSucc = SendSetAdslAction(monitorSetting);
                return CamelCaseJson(new AjaxResult(sendActSucc, sendActSucc ? null : MessageResource.SendActionError));
            }
            return CamelCaseJson(new AjaxResult(false, MessageResource.Save_Error));
        }

        private bool SendSetAdslAction(MonitorSetting monitorSetting)
        {
            var axu = ActionXmlUtility.Instance;
            var ia = new Interactive { InteractiveStatus = InteractiveStatus.Starting, InteractiveType = "SetAdsl" };
            var sr = DataProvider.InteractiveService.Save(ia);
            if (!sr.ExecutedSuccess)
                return false;
            var iaEle = axu.CreateInteractiveElement(ia.Id, "SetAdsl");
            var msEle = axu.CreateSetAdslElement(monitorSetting);
            var actionEle = axu.GeneratorActionXml(axu.CreateActionRootElement(), iaEle, msEle);
            bool sendSucc = Connector.SendAction(actionEle, PresetValues.MonitorIp, PresetValues.MonitorPort);
            if (sendSucc)
            {
                ApplicationContainer.Add(PresetValues.InteractiveKeys.SetAdsl, ia.Id);
                ApplicationContainer.Add(PresetValues.ApplicationKeys.SetAdslTime, DateTime.Now);
            }
            return sendSucc;
        }

        private void RemoveSetAdslCache()
        {
            ApplicationContainer.Remove(PresetValues.InteractiveKeys.SetAdsl);
            ApplicationContainer.Remove(PresetValues.ApplicationKeys.SetAdslTime);
        }

        [HttpPost]
        public ActionResult ReadAdsl(long msId)
        {
            var iaId = ApplicationContainer.Read<long?>(PresetValues.InteractiveKeys.GetAdsl);
            Interactive interactive = iaId.HasValue ? DataProvider.InteractiveService.GetModelById(iaId.Value) : null;
            if (interactive != null)
            {
                if (interactive.InteractiveStatus == InteractiveStatus.End)
                {
                    var monitorSetting = DataProvider.MonitorSettingService.GetModelById(msId);
                    if (monitorSetting != null)
                    {
                        RemoveGetAdslCache();
                        return
                            CamelCaseJson(new AjaxResult(true)
                                {
                                    Expandos =
                                        new
                                            {
                                                monitorSetting.DataPVCVCI,
                                                monitorSetting.DataPVCVPI,
                                                monitorSetting.IptvPVCVCI,
                                                monitorSetting.IptvPVCVPI
                                            }
                                });
                    }
                }
                var readAdslTime = ApplicationContainer.Read<DateTime>(PresetValues.ApplicationKeys.GetAdslTime);
                var timeSpan = DateTime.Now - readAdslTime;
                if (timeSpan.TotalSeconds >= PresetValues.Timeouts.GetAdsl)
                {
                    RemoveGetAdslCache();
                    SaveInteractiveTimeout(interactive);
                    return CamelCaseJson(new AjaxResult(false, "读取ADSL信息超时"));
                }
                return CamelCaseJson(AjaxResult.TrueResult);
            }
            //iaId不存在application中，启动读取adsl信息
            interactive = new Interactive
                {
                    InteractiveStatus = InteractiveStatus.Starting,
                    InteractiveType = "ReadAdsl"
                };
            var sr = DataProvider.InteractiveService.Save(interactive);
            if (sr.ExecutedSuccess)
            {
                var axu = ActionXmlUtility.Instance;
                var interactiveEle =
                    axu.CreateInteractiveElement(interactive.Id, "ReadAdsl");
                var getAdslEle = axu.CreateGetAdslElement(msId);
                var actionEle =
                    axu.GeneratorActionXml(axu.CreateActionRootElement(), interactiveEle, getAdslEle);
                if (!Connector.SendAction(actionEle, PresetValues.MonitorIp, PresetValues.MonitorPort))
                    return CamelCaseJson(new AjaxResult(false, MessageResource.SendActionError));
                ApplicationContainer.Add(PresetValues.ApplicationKeys.GetAdslTime, DateTime.Now);
                ApplicationContainer.Add(PresetValues.InteractiveKeys.GetAdsl, interactive.Id);
                return CamelCaseJson(AjaxResult.TrueResult);
            }
            return CamelCaseJson(new AjaxResult(false, sr.Message));
        }

        private void RemoveGetAdslCache()
        {
            ApplicationContainer.Remove(PresetValues.ApplicationKeys.GetAdslTime);
            ApplicationContainer.Remove(PresetValues.InteractiveKeys.GetAdsl);
        }

        public ActionResult AlertSetting()
        {
            IEnumerable<AlertSetting> alertSettings =
                DataProvider.AlertSettingService.GetAllModels(true).GroupBy(p => p.AlertType).Select(p => p.FirstOrDefault());
            return View(alertSettings);
        }

        [HttpPost]
        public ActionResult AlertSetting([JsonBinder]AlertSetting[] alertSettings)
        {
            var alertEle = ActionXmlUtility.Instance.CreateAlertElement(alertSettings);
            var actionEle =
                ActionXmlUtility.Instance.GeneratorActionXml(ActionXmlUtility.Instance.CreateActionRootElement(),
                                                             alertEle);
            if (!Connector.SendAction(actionEle, PresetValues.MonitorIp, PresetValues.MonitorPort))
            {
                ModelState.AddModelError("", MessageResource.SendActionError);
                return View(alertSettings);
            }
            var serviceResult = DataProvider.AlertSettingService.SaveAll(alertSettings);
            if (serviceResult.ExecutedSuccess)
            {
                ModelState.AddModelError("", MessageResource.Save_Success);
                var alertStsInDb =
                    DataProvider.AlertSettingService.GetAllModels(true)
                                .GroupBy(p => p.AlertType)
                                .Select(p => p.FirstOrDefault());
                return View(alertStsInDb);
            }
            ModelState.AddModelError("", MessageResource.Save_Error);
            return View(alertSettings);
        }

        public ActionResult IpSetting()
        {
            var ipSetting = DataProvider.IpSettingService.GetLastIpSetting(PresetValues.NetWorkCardName);
            return View(ipSetting);
        }

        [HttpPost]
        public ActionResult IpSetting(IpSetting ipSetting)
        {
            if (ModelState.IsValid)
            {
                var serviceResult = DataProvider.IpSettingService.Save(ipSetting);
                if (serviceResult.ExecutedSuccess)
                {
                    var setServerIpEle = ActionXmlUtility.Instance.CreateSetServerIpElement(ipSetting);
                    var actionEle =
                        ActionXmlUtility.Instance.GeneratorActionXml(
                            ActionXmlUtility.Instance.CreateActionRootElement(), setServerIpEle);
                    if (Connector.SendAction(actionEle, PresetValues.MonitorIp, PresetValues.MonitorPort))
                    {
                        ModelState.AddModelError("", MessageResource.Save_Success);
                        return View(ipSetting);
                    }
                    ModelState.AddModelError("", MessageResource.SendActionError);
                }
            }
            ModelState.AddModelError("", MessageResource.Save_Error);
            return View(ipSetting);
        }

        [HttpPost]
        public ActionResult StartScan()
        {
            var interactive = new Interactive
                {
                    InteractiveStatus = InteractiveStatus.Starting,
                    InteractiveType = "ScanningServerIp"
                };
            var serviceResult = DataProvider.InteractiveService.Save(interactive);
            if (serviceResult.ExecutedSuccess)
            {
                var interactiveEle =
                    ActionXmlUtility.Instance.CreateInteractiveElement(interactive.Id, "ScanningServerIp");
                var scanServerIpEle = ActionXmlUtility.Instance.CreateLocalIpElement();
                var actionElement =
                    ActionXmlUtility.Instance.GeneratorActionXml(ActionXmlUtility.Instance.CreateActionRootElement(),
                                                                 interactiveEle, scanServerIpEle);
                if (!Connector.SendAction(actionElement, PresetValues.MonitorIp, PresetValues.MonitorPort))
                {
                    return Json(new AjaxResult(false, MessageResource.SendActionError));
                }
                ApplicationContainer.Add(PresetValues.ApplicationKeys.ScanStartTime, DateTime.Now);
                ApplicationContainer.Add(PresetValues.InteractiveKeys.ServerIpScanning, interactive.Id);
                return Json(AjaxResult.TrueResult);
            }
            return Json(new AjaxResult(false, serviceResult.Message));
        }

        [HttpPost]
        public ActionResult ScanServerIp()
        {
            long? interactiveId = ApplicationContainer.Read<long?>(PresetValues.InteractiveKeys.ServerIpScanning);
            if (interactiveId.HasValue)
            {
                var interactiveModel = DataProvider.InteractiveService.GetModelById(interactiveId.Value);
                
                if (interactiveModel != null && interactiveModel.InteractiveStatus == InteractiveStatus.End)
                {
                    var ipSetting = DataProvider.IpSettingService.GetLastIpSetting(PresetValues.NetWorkCardName);
                    ApplicationContainer.Remove(PresetValues.ApplicationKeys.ScanStartTime);
                    ApplicationContainer.Remove(PresetValues.InteractiveKeys.ServerIpScanning);
                    return
                        Json(new AjaxResult(true)
                            {
                                Expandos = new { ipSetting.Ip, ipSetting.SubnetMask, ipSetting.Gateway }
                            });
                }
                DateTime? startTime = ApplicationContainer.Read<DateTime?>(PresetValues.ApplicationKeys.ScanStartTime);
                if (startTime.HasValue && (DateTime.Now - startTime.Value).TotalSeconds >= PresetValues.Timeouts.ScanServerIp)
                {
                    ApplicationContainer.Remove(PresetValues.ApplicationKeys.ScanStartTime);
                    ApplicationContainer.Remove(PresetValues.InteractiveKeys.ServerIpScanning);
                    return Json(new AjaxResult(false, "扫描超时"));
                }
                return Json(new AjaxResult(true));
            }
            return Json(new AjaxResult(false, "未开始扫描"));
        }

        [HttpPost]
        public ActionResult CheckSvrIpSetting(IpSetting ipSetting)
        {
            var itactId = ApplicationContainer.Read<long?>(PresetValues.InteractiveKeys.SetSvrIp);
            var itact = itactId.HasValue
                            ? DataProvider.InteractiveService.GetModelById(itactId.Value)
                            : null;
            if (itact != null)
            {
                if (itact.InteractiveStatus == InteractiveStatus.Error)
                {
                    RemoveCheckSvrIpCache();
                    DataProvider.IpSettingService.Save(ipSetting);
                    return
                        CamelCaseJson(new AjaxResult(false,
                                                     XmlResource.GetItactCodeValue(itact.ErrorCode)));
                }
                if (itact.InteractiveStatus == InteractiveStatus.End)
                {
                    RemoveCheckSvrIpCache();
                    return CamelCaseJson(new AjaxResult(true) { Expandos = new { IsValid = true } });
                }
                var startTime =
                    ApplicationContainer.Read<DateTime>(PresetValues.ApplicationKeys.SetSvrIpTime);
                if ((DateTime.Now - startTime).TotalSeconds >= PresetValues.Timeouts.SetSvrIp)
                {
                    SaveInteractiveTimeout(itact);
                    RemoveCheckSvrIpCache();
                    return CamelCaseJson(new AjaxResult(false, "设置IP地址超时"));
                }
                return CamelCaseJson(AjaxResult.TrueResult);
            }
            itact = new Interactive
            {
                InteractiveStatus = InteractiveStatus.Starting,
                InteractiveType = "SetSvrIp"
            };
            var sr = DataProvider.InteractiveService.Save(itact);
            if (sr.ExecutedSuccess)
            {
                var setServerIpEle = ActionXmlUtility.Instance.CreateSetServerIpElement(ipSetting);
                var itactEle = ActionXmlUtility.Instance.CreateInteractiveElement(itact.Id, "SetSvrIp");
                var actionEle =
                    ActionXmlUtility.Instance.GeneratorActionXml(
                        ActionXmlUtility.Instance.CreateActionRootElement(), itactEle, setServerIpEle);
                if (!Connector.SendAction(actionEle, PresetValues.MonitorIp, PresetValues.MonitorPort))
                    return CamelCaseJson(new AjaxResult(false, MessageResource.SendActionError));
                ApplicationContainer.Add(PresetValues.InteractiveKeys.SetSvrIp, itact.Id);
                ApplicationContainer.Add(PresetValues.ApplicationKeys.SetSvrIpTime, DateTime.Now);
                return CamelCaseJson(AjaxResult.TrueResult);
            }
            return CamelCaseJson(new AjaxResult(false, sr.Message));
        }

        private void RemoveCheckSvrIpCache()
        {
            ApplicationContainer.Remove(PresetValues.InteractiveKeys.SetSvrIp);
            ApplicationContainer.Remove(PresetValues.ApplicationKeys.SetSvrIpTime);
        }

        public ActionResult KeywordTemplateManage(int pageIndex = 1)
        {
            var keywordTemplates =
                DataProvider.KeywordService.GetAllKeywordsInTemplate()
                            .ToPagedList(pageIndex, PresetValues.DefaultPageSize);
            return View(keywordTemplates);
        }

        public ActionResult RemoteControl()
        {
            var rmctl = DataProvider.RemoteServerService.GetLastRemoteSvr();
            return View(rmctl ?? new RemoteServer());
        }

        [HttpPost]
        public ActionResult RemoteControl(RemoteServer remoteServer)
        {
            if ((remoteServer != null && remoteServer.StatusToken == 0) || ModelState.IsValid)
            {
                if (remoteServer != null && remoteServer.StatusToken == 0 && remoteServer.Id > 0
                    && !ModelState.IsValid)
                {
                    remoteServer = DataProvider.RemoteServerService.GetModelById(remoteServer.Id);
                    remoteServer.StatusToken = 0;
                    ModelState.Clear();
                }
                var sr = DataProvider.RemoteServerService.Save(remoteServer);
                ModelState.AddModelError("",
                                         sr.ExecutedSuccess
                                             ? MessageResource.Save_Success
                                             : sr.Message);
            }
            else
                ModelState.AddModelError("", MessageResource.IsNotValid);
            return View(remoteServer);
        }

        [HttpPost]
        public ActionResult CheckRmSvr(RemoteServer remoteServer)
        {
            var itactId = ApplicationContainer.Read<long?>(PresetValues.InteractiveKeys.SetRmSvr);
            var itact = itactId.HasValue
                            ? DataProvider.InteractiveService.GetModelById(itactId.Value)
                            : null;
            if (itact != null)
            {
                if (itact.InteractiveStatus == InteractiveStatus.Error)
                {
                    RemoveSetRmSvrCache();
                    //todo:可能需要保存远程服务器设置到数据库
                    return
                        CamelCaseJson(new AjaxResult(false,
                                                     XmlResource.GetItactCodeValue(itact.ErrorCode)));
                }
                if (itact.InteractiveStatus == InteractiveStatus.End)
                {
                    RemoveSetRmSvrCache();
                    return CamelCaseJson(new AjaxResult(true) { Expandos = new { IsValid = true } });
                }
                var startTime =
                    ApplicationContainer.Read<DateTime>(PresetValues.ApplicationKeys.SetRmSvrTime);
                if ((DateTime.Now - startTime).TotalSeconds >= PresetValues.Timeouts.SetRmSvr)
                {
                    SaveInteractiveTimeout(itact);
                    RemoveSetRmSvrCache();
                    return CamelCaseJson(new AjaxResult(false, "设置远程控制超时"));
                }
                return CamelCaseJson(AjaxResult.TrueResult);
            }
            itact = new Interactive
            {
                InteractiveStatus = InteractiveStatus.Starting,
                InteractiveType = "SetRcontrol"
            };
            var sr = DataProvider.InteractiveService.Save(itact);
            if (sr.ExecutedSuccess)
            {
                var setRmSvrEle = ActionXmlUtility.Instance.CreateRmSvrElement(remoteServer);
                var itactEle = ActionXmlUtility.Instance.CreateInteractiveElement(itact.Id, "SetRcontrol");
                var actionEle =
                    ActionXmlUtility.Instance.GeneratorActionXml(
                        ActionXmlUtility.Instance.CreateActionRootElement(), itactEle, setRmSvrEle);
                if (!Connector.SendAction(actionEle, PresetValues.MonitorIp, PresetValues.MonitorPort))
                    return CamelCaseJson(new AjaxResult(false, MessageResource.SendActionError));
                ApplicationContainer.Add(PresetValues.InteractiveKeys.SetRmSvr, itact.Id);
                ApplicationContainer.Add(PresetValues.ApplicationKeys.SetRmSvrTime, DateTime.Now);
                return CamelCaseJson(AjaxResult.TrueResult);
            }
            return CamelCaseJson(new AjaxResult(false));
        }

        private void RemoveSetRmSvrCache()
        {
            ApplicationContainer.Remove(PresetValues.ApplicationKeys.SetRmSvrTime);
            ApplicationContainer.Remove(PresetValues.InteractiveKeys.SetRmSvr);
        }
    }
}
